// 租户登录的页面
import React, { useRef, useEffect, useState } from 'react';
import { connect } from 'dva';
import { getMenu } from '@/services/login';
import { Form, Input, Button } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { history } from 'umi';
import { filterMenuTree } from '@/utils/utils';
import styles from './index.less';

type LoginParamsType = {
  userName: string;
  password: string;
  captcha: string;
};
interface LoginProps {
  loginHandle: (params: LoginParamsType, callback: (data: any) => void) => void;
  getStatusMap: (parmas: string) => void;
}

const Login: React.FC<LoginProps> = (props) => {
  const { loginHandle, getStatusMap } = props;

  const [loginLoading, setBtnLoginLoading] = useState(false);

  useEffect(() => {
    localStorage.removeItem('authorization');
    localStorage.removeItem('moduleMap');
    localStorage.removeItem('resource');
  }, []);

  const mainRef = useRef<any>();
  const onFinish = (values: any) => {
    //todo 测试
    // let menuTree = filterMenuTree(tempArrData.data.menu[0].children);
    // console.log('menuTree :>> ', menuTree);
    // window.localStorage.setItem('resource', JSON.stringify(menuTree)); //设置功能菜单树
    // window.localStorage.setItem('moduleMap', JSON.stringify(tempArrData.data.perms)); // 功能权限列表
    // history.push('/');
    setBtnLoginLoading(true);
    values.grant_type = 'password';
    values.sub_system_code = 'WEB-0000';
    values.type = 'SYSTEM_USER'; //系统管理员关键字=SYSTEM_USER 否则为租户
    loginHandle(values, (data: any) => {
      // if (data.code == 200) {
      //   window.localStorage.setItem('authorization',data.data.access_token);
      //   getMenu({}).then(res=>{
      //     setBtnLoginLoading(false);
      //     // todo 获取菜单树
      //     console.log('todo 获取菜单树 :>> ', res);
      //     if (res.code == 200) {
      //       let menuTree = filterMenuTree(res.data.menu[0].children);
      //       window.localStorage.setItem('resource', JSON.stringify(menuTree)); //设置功能菜单树
      //       window.localStorage.setItem('moduleMap', JSON.stringify(res.data.perms)); // 功能权限列表
      //       history.push('/');
      //     }
      //   })
      // }else{
      //   setBtnLoginLoading(false);
      // }
      getStatusMap('sys_common_status');
      // 获取权限树
      window.localStorage.setItem('authorization', data.access_token);
      getMenu({}).then((res) => {
        setBtnLoginLoading(false);
        // todo 获取菜单树
        if (res.code == 200) {
          let menuTree = filterMenuTree(res.data.menu[0].children);
          window.localStorage.setItem('resource', JSON.stringify(menuTree)); //设置功能菜单树
          window.localStorage.setItem(
            'moduleMap',
            JSON.stringify(res.data.perms),
          ); // 功能权限列表
          history.push(menuTree[0].children[0].path || '/');
        }
      });
    });
  };
  return (
    <div ref={mainRef} className={styles.main}>
      <div className={styles.container}>
        <img src={require('@/assets/img/logo.jpg')} width="50px" alt="浏览器" />
        <h1 className={styles.title}>PSC公共模块建设</h1>
        <div className={styles.form}>
          <Form
            name="normal_login"
            className="login-form"
            size="large"
            initialValues={{ remember: true }}
            onFinish={onFinish}
          >
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入您的用户名!' }]}
              initialValue=""
            >
              <Input
                // prefix={<UserOutlined className="site-form-item-icon" />}
                placeholder="用户名"
              />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入您的密码!' }]}
              initialValue=""
            >
              <Input.Password
                // prefix={<LockOutlined className="site-form-item-icon" />}
                type="password"
                placeholder="密码"
              />
            </Form.Item>
            <Form.Item
              name="captcha"
              rules={[{ required: true, message: '请输入验证码!' }]}
              initialValue=""
            >
              <div className={styles['flex-row-justify']}>
                <Input placeholder="请输入验证码" />
                <div className={styles.captchaImg}>验证码</div>
              </div>
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                loading={loginLoading}
                onClick={() => {
                  console.log(1111);
                }}
                className={styles['login-form-button']}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>

      <div className={styles.footer}>
        <p>
          版权所属：成都民航西南凯亚 蜀ICP备10000000号-1
          当前版本：PSIS_2.2.20_20200511_release
        </p>
        <p className={styles.footerTips}>
          <img src={require('@/assets/img/smalllogo.png')} alt="浏览器" />
          推荐浏览器下载：谷歌浏览器 火狐浏览器 360极速浏览器
          <img
            src={require('@/assets/img/iphone.png')}
            alt="ipad"
            style={{ marginLeft: '36px' }}
          />
          IPAD端程序下载
        </p>
      </div>
    </div>
  );
};

const mapStateToProps = (state: any) => {
  return {
    status: state.login.status,
  };
};

const mapDispatchToProps = (dispatch: any) => {
  return {
    loginHandle(msg: LoginParamsType, callbackData: any) {
      dispatch({
        type: 'login/login',
        payload: msg,
        callback: (res: any) => {
          callbackData(res);
        },
        onerror: (err: any) => {
          console.log(err);
        },
      });
    },
    getStatusMap(params: string) {
      dispatch({
        type: 'common/getStatusMap',
        payload: params,
      });
    },
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Login);
